﻿using FrameWork.Request;
using Microsoft.AspNetCore.Http;
using System.IO;

namespace Service.System
{
    public class UpLoadService
    {
        /**
         * 附件上传
         */
        public async Task<string> FileUpload(IFormFile file)
        {
            //判断文件是否有效
            if (file == null)
            {
                return null;
            }

            ////获取文件名并存储
            //var fileName = Path.GetFileName(file.FileName);
            //var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Uploads", fileName);

            ////确保上传目录存在
            //Directory.CreateDirectory(Path.GetDirectoryName(filePath));

            ////保存文件
            //using (var stream = new FileStream(filePath, FileMode.Create))
            //{
            //    await file.CopyToAsync(stream);
            //}
            var savepath = string.Format("K:\\picture");
            //var savepath = string.Format("{0}\\{1}\\{2}", Directory.GetCurrentDirectory(), "Uploads", DateTime.Now.ToString("yyyy-MM-dd"));
            #region 保存路径，如果不存在则创建
            if (!Directory.Exists(savepath))
            {
                Directory.CreateDirectory(savepath);
            }
            #endregion
            //文件信息
            string filename = Path.GetFileNameWithoutExtension(file.FileName);
            var extension = Path.GetExtension(file.FileName);


            //保留文件名
            var newName = filename;
            int i = 1;
            while (true)
            {
                if (File.Exists(savepath + "\\" + newName + extension))
                {
                    newName = filename + "（" + i + "）";
                    i++;
                }
                else
                {
                    filename = newName;
                    break;
                }
            }

            var imagepath = string.Format("{0}\\{1}{2}", savepath, filename, extension);
            using (var stream = file.OpenReadStream())
            {
                using (var fs = new FileStream(imagepath, FileMode.CreateNew))
                {
                    stream.CopyTo(fs);
                }
            }
            //返回
            //return RequestResponse.CreateResponse(200, "上传成功", string.Format("{0}{1}{2}", string.Format("/{0}/{1}/{2}/", Directory.GetCurrentDirectory(), "Uploads", DateTime.Now.ToString("yyyy-MM-dd")), filename, extension));
            //return  string.Format("{0}{1}{2}", string.Format("/{0}/{1}/{2}/", Directory.GetCurrentDirectory(), "Uploads", DateTime.Now.ToString("yyyy-MM-dd")), filename, extension);
            return  string.Format("{0}{1}", filename, extension);
        }
    }
}
